package com.attempt.grab.constant;

import lombok.SneakyThrows;
import org.springframework.web.socket.*;

/**
 * @author xuhaifeng
 * @since 2022年02月25日 下午 1:29
 */
@SuppressWarnings("unused")
public record WebSocketSessionSender(WebSocketSession session) {
    /**
     * 初始化Web套接字发送器
     * Instantiates a new Web socket sender.
     *
     * @param session the session
     */
    public WebSocketSessionSender {
    }

    /**
     * 发送数据
     *
     * @param data the data
     */
    @SneakyThrows
    public void sendData(byte[] data) {
        if (session.isOpen()) {
            synchronized (session) {
                session.sendMessage(new BinaryMessage(data));
            }
        }
    }

    /**
     * 发送数据
     *
     * @param data the data
     */
    @SneakyThrows
    public void sendData(String data) {
        if (session.isOpen()) {
            synchronized (session) {
                session.sendMessage(new TextMessage(data));
            }
        }
    }

    /**
     * 发送数据
     */
    @SneakyThrows
    public void sendPingData() {
        if (session.isOpen()) {
            synchronized (session) {
                session.sendMessage(new PingMessage());
            }
        }
    }

    /**
     * 发送数据
     */
    @SneakyThrows
    public void sendPongData() {
        if (session.isOpen()) {
            synchronized (session) {
                session.sendMessage(new PongMessage());
            }
        }
    }

    /**
     * 关闭会话
     */
    @SneakyThrows
    public void closeSession() {
        if (session.isOpen()) {
            synchronized (session) {
                session.close();
            }
        }
    }
}
